package com.ruoyi.user.aspect;

import com.ruoyi.common.core.exception.user.Result;
import com.ruoyi.user.entity.Log;
import com.ruoyi.user.mapper.LogMapper;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Author: 张桦阳
 * @Date: 2023-03-22-20:29:15
 * @Description: 类
 */
@Aspect
@Component
public class LogAspect {

    @Resource
    private LogMapper logMapper;

    @AfterReturning(value = "execution(* *..controller.*.login(..))", returning = "result")
    public void loginLog(Result result) {
        // 获取 HttpServletRequest 对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        // 如果登录成功就插入登录日志信息数据
        if (result.isStatus()){
            // 创建日志对象
            Log log = new Log();
            // 获取 IP 地址
            String addr = request.getRemoteAddr();
            // UserContext.getEmployee() 是我写的一个工具方法，你自己写一个就好了
            // 也就是把员工的数据存入到实体对象的字段上，后面连表查询方便
            Map map = (Map) result.getData();
            log.setUsername((String) map.get("username"));
            log.setLoginStatus(result.getMessage());
            log.setLoginTime(new Date());
            log.setLoginIp(addr);
            // 把登录日志信息存到数据库
            logMapper.insert(log);
        }
    }
}